from django.http import HttpResponse, HttpResponseBadRequest
from django.http import JsonResponse
from django.views.decorators.http import etag

from Apis.Utils.forms import *

import requests, json, random, hashlib


def poem(request):
    url = 'http://cloud.deali.cn/poem.php'
    res = requests.get(url)
    return HttpResponse(res.content.decode('utf-8'))


def generate_etag(req, width, height):
    content = 'Placeholder: {0}x{1}'.format(width, height)
    return hashlib.sha1(content.encode('utf-8')).hexdigest()


@etag(generate_etag)
def placeholder(request, width, height):
    """生成占位图片"""
    form = ImageForm({'width': width, 'height': height})
    if form.is_valid():
        image = form.generate()
        return HttpResponse(image, content_type='image/png')
    else:
        return HttpResponseBadRequest('图片格式错误')


def img_url(request, width, height):
    rnd = random.Random()
    url = 'https://picsum.photos/{}/{}?rnd={}'.format(width, height, rnd.randint(0, 100))
    return HttpResponse(url)


def hitokoto(request):
    url = 'http://dc.deali.cn/api/hitokoto/get'
    res = requests.get(url)
    obj = json.loads(res.content.decode('utf-8'))
    return JsonResponse(obj, safe=False, json_dumps_params={'ensure_ascii': False})
